<?php
session_start(); //we need to call PHP's session object to access it through CI
class kelas extends CI_Controller {

	function __construct()
	{
		parent::__construct();
		$this->data['menu'] = 'kelas';
		$this->data['form'] = 'custom/form_kelas';
		$this->data['title'] = 'Kelas';
	}

	function index()
	{
		$params = array('tablename' => 'kelas', 'primary_key' => 'kl_id');
		$this->load->library('grid', $params);
		$this->grid->add_subject('Mata Pelajaran');
		$this->grid->add_field('kl_name', 'Nama Kelas','', 'show');
		$this->grid->add_field('kl_rank', 'Tingkat','', 'show');
		$this->grid->set_menu('kelas');
		$this->grid->set_form('form_mp');
		$this->grid->set_portlet_style('portlet box purple');
		$this->grid->set_portlet_title('Data Kelas');
		$this->grid->show();
	}

	function form_value(){
		$value['kl_name'] = $this->input->post('kl_name');
		$value['kl_rank'] = $this->input->post('kl_rank');
		return $value;
	}
	
	function init_data_form(){
		$this->data['kl_name'] = '';
		$this->data['kl_rank'] = '0';
	}

	function add(){
		$this->init_data_form();
		$this->data['portlet_style'] = 'portlet box yellow';
		$this->data['portlet_title'] = 'Tambah Data Kelas';
		$this->data['action'] = base_url().'kelas/action/insert';
		$this->data['portlet_type'] = 'Form';
		$this->data['id'] = '';
		$this->load();
	}

	function action(){
		$act = $this->uri->segment(3);
		$value = $this->form_value();
		$this->load->model('m_kelas');
		$id = $this->input->post('kl_id');
		switch ($act){
			case "insert":
				$res = $this->m_kelas->insert($value);
				$loc = 'kelas/add';
				break;
			case "update":
				$res = $this->m_kelas->update($value, array('kl_id' => $id));
				$loc = 'kelas/update/'.$id;
				break;
		}
		if($res=='1'){
			redirect('kelas');
		}else{
			$this->data['error_message'] = 'Gagal';
			redirect($loc);
		}
	}
	
	function update($id){
		$this->load->model('m_kelas');
		$row = (array)$this->m_kelas->get_data_by_id($id);
		$this->data = array_merge($row, $this->data);
		$this->data['portlet_style'] = 'portlet box green';
		$this->data['portlet_title'] = 'Update Data Kelas';
		$this->data['action'] = base_url().'kelas/action/update';
		$this->data['portlet_type'] = 'Form';
		$this->data['id'] = $id;
		$this->load();
		//print_r($this->data);
	}	
	
	function delete($id){
		$this->load->model('m_kelas');
		$res = $this->m_kelas->delete(array('kl_id' => $id));
		if($res!='1'){
			$this->data['error_message'] = 'Gagal';
		}
		redirect('kelas');
	}

	function load(){
		if($this->session->userdata('admin')){
			$session_data = $this->session->userdata('admin');
			$this->data['username'] = $session_data['username'];
			$this->data['nama'] = $session_data['nama'];
			$this->load->view('main', $this->data);
		}else{
			redirect('admin', 'refresh');
		}
	}

}
?>